<script setup lang="ts">
import { getPointsGiftAPI, submitExchangeRecordAPI } from '@/services/points'
import type { GiftItem } from '@/types/gift'
import type { PageParams } from '@/types/global'
import { ref, onMounted } from 'vue'
import PageSkeleton from './components/PageSkeleton.vue'
import { useMemberStore } from '@/stores'
const memberStore = useMemberStore()

const giftList = ref<GiftItem[]>([])
const pageParams = ref<PageParams>({
  pageNum: 1,
  pageSize: 10,
})
const hasMore = ref(true)
const isTriggered = ref(false)
const isFinish = ref(false)
const loading = ref(false)
const getCategoryTopData = async () => {
  const res = await getPointsGiftAPI(pageParams.value)
  // 添加数据
  if (pageParams.value.pageNum === 1) {
    giftList.value = res.data.rows
  } else {
    giftList.value = [...giftList.value, ...res.data.rows]
  }
  // 判断是否还有更多数据
  hasMore.value = res.data.rows.length === pageParams.value.pageSize
  // 更新页码
  pageParams.value.pageNum = (pageParams.value.pageNum || 1) + 1
}

// 页面加载
onMounted(async () => {
  await Promise.all([getCategoryTopData()])
  isFinish.value = true
})
// 下拉刷新
const onRefresherrefresh = async () => {
  isTriggered.value = true
  // 根据当前标签刷新对应数据
  pageParams.value.pageNum = 1
  pageParams.value.pageSize = 10
  await getCategoryTopData()
  isTriggered.value = false
}
// 上拉加载更多
const handleLoadMore = async () => {
  if (hasMore.value) {
    pageParams.value.pageNum = (pageParams.value.pageNum ?? 1) + 1
    await getCategoryTopData()
  }
}
// 兑换礼品函数
const exchangeGift = async (gift: GiftItem) => {
  if (memberStore.profile) {
    const currentPoints = memberStore.profile.points || 0
    if (currentPoints < gift.price) {
      uni.showToast({
        title: '积分不足',
        icon: 'none',
        duration: 2000,
      })
      return
    }
    memberStore.profile.points = currentPoints - gift.price
  }

  // 显示确认弹窗
  const { confirm } = await uni.showModal({
    title: '兑换确认',
    content: `确定要使用${gift.price}积分兑换${gift.name}吗？`,
    confirmText: '确认兑换',
    cancelText: '取消',
  })

  if (confirm) {
    // 显示加载状态
    loading.value = true
    try {
      // 提交兑换记录
      const res = await submitExchangeRecordAPI({
        giftId: gift.id,
      })

      // 处理结果
      if (res.code === 200) {
        uni.showToast({
          title: '兑换成功',
          icon: 'success',
          duration: 2000,
        })

        // 刷新礼品列表或跳转到兑换记录页面
        // 这里选择刷新礼品列表
        pageParams.value.pageNum = 1
        await getCategoryTopData()
      } else {
        uni.showToast({
          title: res.msg || '兑换失败',
          icon: 'none',
          duration: 2000,
        })
      }
    } catch (error) {
      uni.showToast({
        title: '网络错误，请重试',
        icon: 'none',
        duration: 2000,
      })
    } finally {
      // 隐藏加载状态
      loading.value = false
    }
  }
}
</script>

<template>
  <view class="viewport" v-if="isFinish">
    <view class="categories">
      <scroll-view
        class="secondary"
        :enable-back-to-top="true"
        :refresher-enabled="true"
        @refresherrefresh="onRefresherrefresh"
        :refresher-triggered="isTriggered"
        @scrolltolower="handleLoadMore"
        :scroll-y="true"
      >
        <!-- 内容区域 -->
        <view class="panel">
          <view class="section">
            <navigator v-for="gift in giftList" :key="gift.id" class="goods" hover-class="none">
              <image class="image" :src="gift.picture"></image>
              <view class="name ellipsis">{{ gift.name }}</view>
              <view class="info-container">
                <view class="price">
                  <image class="point-image" src="@/static/images/points.png"></image>
                  <text class="number">{{ gift.price }}</text>
                </view>
                <view class="exchange-btn-container">
                  <button
                    class="exchange-btn"
                    hover-class="button-hover"
                    @click.stop="exchangeGift(gift)"
                    :disabled="loading"
                  >
                    兑换
                  </button>
                </view>
              </view>
            </navigator>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
  <PageSkeleton v-else />
</template>

<style lang="scss">
@import './styles/points.scss';
</style>
